package com.tencent.wxcloudrun.config;


import cn.hutool.http.HttpStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolationException;

/**
 * @author xk奇ji
 */
@Slf4j
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ApiResponse<String> handleException(Exception e) {
        e.printStackTrace();
        return new ApiResponse<>(HttpStatus.HTTP_INTERNAL_ERROR, "服务器错误。", null);
    }

    @ExceptionHandler(CustomException.class)
    public ApiResponse<String> handleCustomException(CustomException e) {
        e.printStackTrace();
        return new ApiResponse<>(HttpStatus.HTTP_INTERNAL_ERROR, e.getMessage(), null);
    }

    /**
     * @RequestBody 的参数校验
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResponse<String> handleValidationExceptions(MethodArgumentNotValidException ex) {
        String message = ex.getBindingResult().getFieldError().getDefaultMessage();
        return new ApiResponse<>(HttpStatus.HTTP_INTERNAL_ERROR, message, null);
    }

    /**
     * @RequestParam 的参数校验
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ApiResponse<String> handleValidationExceptions(ConstraintViolationException ex) {
        String message = ex.getConstraintViolations().iterator().next().getMessage();
        return new ApiResponse<>(HttpStatus.HTTP_INTERNAL_ERROR, message, null);
    }

}
